<template>
  <div>
    <div v-if="componentIs('potential-clients')"  class="mod-config" id="mod-config-id">
      <div class="div-tabs">
        <div class="div-tabs-item " :class="{'div-tabs-active':tabIs('enterprise')}" @click="clickTabChange('enterprise')"><span >企业客户</span></div>
        <div class="div-tabs-item" :class="{'div-tabs-active':tabIs('personal')}" @click="clickTabChange('personal')"><span >个人客户</span></div>
      </div>
      <div v-if="isAuth('potential:paging')" class="div-s" id="div-s-id">
        <el-form  :model="params" :label-position="labelPosition" ref="queryFormRef" :inline="true" label-width="70px" class="queryFormed">
          <el-row v-if="tabIs('enterprise')" class="row-s" >
            <el-col :span="6" >
              <el-form-item label="信用代码"  prop="certificateCode">
                <el-input v-model="params.certificateCode" placeholder="请输入社会统一信用代码" @clear="clickSearch"    clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="企业名称" >
                <el-input v-model="params.name" placeholder="输入企业名称" @clear="clearName"    clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col  :span="6" >
              <el-form-item label="所在区域"  >
                <el-select v-model="areaSelectValue" placeholder="请选择区域"  @clear="clearArea" @focus="showSelectAreaDialog" clearable no-data-text=" ">
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="isAuth('potential:transfer')" :span="6" class="col-right">
              <el-form-item  label="跟进人"  >
                <el-select v-model="employeeSelectValue" placeholder="请选择部门/人"  @clear="clearEmployee"  @focus="showSelectEmployeeDialog"  clearable no-data-text=" "></el-select>
              </el-form-item>
            </el-col>
            <el-col class="col-right" :span="6" :offset="18">
              <el-form-item class="item-all">
                <el-button class="buttonItem" size="mini" plain @click="clickReset">重 置</el-button>
                <el-button class="buttonItem" size="mini" type="primary" @click="clickSearch">搜 索</el-button>
<!--                <el-button v-if="!isUnfold" @click="turnFoldState" type="text">展开<i
                  class="el-icon-arrow-down zhankai"></i></el-button>
                <el-button v-if="isUnfold" @click="turnFoldState" type="text">收起<i class="el-icon-arrow-up zhankai"></i>
                </el-button>-->
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-show="tabIs('personal')" class="row-s" >
            <el-col v-if="isAuth('potential:transfer')" :span="6">
              <el-form-item label="跟进人"  >
                <el-select v-model="employeeSelectValue" placeholder="请选择部门/人"  @clear="clearEmployee"  @focus="showSelectEmployeeDialog"  clearable no-data-text=" "></el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系人" >
                <el-input v-model="params.contactsName" placeholder="请输入联系人" @clear="clearContactsName"    clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="手机号" >
                <el-input v-model="params.contactsMobile" placeholder="请输入联系人手机号" @clear="clearContactsMobile"    clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col class="col-right" :span="6" >
              <el-form-item class="item-all">
                <el-button class="buttonItem" size="mini" plain @click="clickReset">重 置</el-button>
                <el-button class="buttonItem" size="mini" type="primary" @click="clickSearch">搜 索</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="div-e" id="div-e-id">
        <div class="div-inquire" id="div-inquire-id">
          <div class="in-t">
            <div class="in-ts"></div>
            <h3 >意向客户</h3>
          </div>
          <div  class="div-button">
            <batch-import :type="tabsFlag === 'enterprise' ? 1 : 0" :customerType="2" v-if="isAuth('potential:import')" @refreshData="refreshData"></batch-import>
<!--            <el-button v-if="isAuth('ent:customer:personImport')" size="mini" type="primary" icon="el-icon-download" @click="">数据导入</el-button>-->
            <el-button v-if="isAuth('potential:export')" size="mini" type="primary" icon="el-icon-upload2" @click="clickExport">数据导出</el-button>
            <el-button v-if="isAuth('potential:transfer')" size="mini" type="primary"  @click="showSelectEmployeeTransferDialog" :disabled="customerIdList.length <1">批量转让</el-button>
            <el-button v-if="isAuth('potential:save')" size="mini" type="primary" icon="el-icon-plus" @click="clickAdd">新增</el-button>
          </div>
        </div>
        <el-table
          v-if="tabIs('enterprise')"
          ref="multipleTable"
          :data="tableData"
          :max-height="table.tableHeight"
          :header-cell-style="{background:'#F5F7FA'}"
          :cell-style="{'border-right': 'none','border-left': 'none'}"
          style="width: 100%"
          v-loading="dataListLoading"
          @selection-change="enterpriseHandleSelectionChange"
          @sort-change='sortChange'
          border
          fit>
          <el-table-column
            type="selection"
            width="55"
          fixed>
          </el-table-column>
          <el-table-column
            label="序号"
            type="index"
            width="50"
            align="center"
            fixed>
          </el-table-column>
          <el-table-column
            label="公司名称"
            width="280"
            prop="name"
            align="center"
            show-overflow-tooltip
          fixed>

          </el-table-column>
<!--          <el-table-column
            label="信用代码"
            width="280"
            prop="certificateCode"
            align="center"
            fixed>
          </el-table-column>-->
          <el-table-column
            prop="areaName"
            label="所在区域"
            width="100"
            align="center"
          fixed>
          </el-table-column>
<!--          <el-table-column
            prop="addressDetail"
            label="详细地址"
            width="200"
            align="center"
          show-overflow-tooltip>
          </el-table-column>-->
          <el-table-column
            prop="contactsName"
            label="联系人"
            width="80"
            align="center"
          show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="contactsPosition"
            label="职务"
            width="80"
            align="center"
            sortable='custom'
          show-overflow-tooltip>
          </el-table-column>
<!--          <el-table-column
            prop="contactsMobile"
            label="联系人电话"
            width="200"
            align="center">
          </el-table-column>-->
          <el-table-column
            prop="followUserName"
            label="跟进人"
            width="120"
            align="center"
            sortable='custom'
          show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="lastFollow"
            label="最新跟进"
            align="center"
            min-width="200"
          show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            align="center"
            min-width="200"
            sortable='custom'
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            label="操作"
            min-width="110"
            style="max-width: 120px"
            align="center">
            <template slot-scope="scope">
              <el-button type="text" size="mini" style="color: #66b1ff" @click="clickShowDetails('ent-details',scope.row)">跟进</el-button>
              <span style="color:#E8E8E8;">|</span>
              <el-popover
                placement="bottom"
                :visible-arrow="false"
                popper-class="popper-style">
                <div style="text-align: center; margin: 0; display: flex;flex-direction: column;font-size: 12px">
                  <div v-if="" @click="turnToFinishReq(scope.row)" class="popover-item" >转成交</div>
                  <div v-if="isAuth('potential:transfer')" @click="clickTransferSingle(scope.row)" class="popover-item" >转让</div>
                  <div v-if="isAuth('potential:delete')" @click="clickDelete(scope.row)" class="popover-item">删除</div>
                </div>
                <el-button  type="text" size="mini" slot="reference" @click="" style="color: #66b1ff"  >更多<i class="el-icon-arrow-down"></i></el-button>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
        <el-table
          v-if="tabIs('personal')"
          ref="multipleTable"
          :data="tableData"
          :max-height="table.tableHeight"
          :header-cell-style="{background:'#F5F7FA'}"
          style="width: 100%"
          v-loading="dataListLoading"
          @selection-change="personalHandleSelectionChange"
          @sort-change="sortChange"
          fit>
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            label="序号"
            type="index"
            width="50"
            align="center">
          </el-table-column>
          <el-table-column
            label="姓名"
            width="200"
            prop="name"
            align="center">
          </el-table-column>
          <el-table-column
            prop="contactsMobile"
            label="联系方式"
            align="center">
          </el-table-column>
          <el-table-column
            prop="mailingAddress"
            label="邮寄地址"
            align="center">
          </el-table-column>
          <el-table-column
            prop="totalCost"
            label="消费总额(元)"
            align="center">
          </el-table-column>
          <el-table-column
            prop="costAmount"
            label="消费次数"
            align="center">
          </el-table-column>
          <el-table-column
            prop="lastFollow"
            label="最新跟进"
            align="center"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            align="center"
            min-width="200"
            sortable='custom'
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center">
            <template slot-scope="scope">
              <el-button type="text" style="color: #66b1ff" @click="clickShowDetails('personal-details',scope.row)">跟进</el-button>
              <span style="color:#E8E8E8;">|</span>
              <el-popover
                placement="bottom"
                :visible-arrow="false"
                popper-class="popper-style">
                <div style="text-align: center; margin: 0; display: flex;flex-direction: column">
                  <div v-if="" @click="turnToFinishReq(scope.row)" class="popover-item" >转成交</div>
                  <div v-if="isAuth('potential:transfer')" @click="clickTransferSingle(scope.row)"  class="popover-item" >转让</div>
                  <div v-if="isAuth('potential:delete')" @click="clickDelete(scope.row)" class="popover-item">删除</div>
                </div>
                <el-button  type="text" slot="reference" @click="" style="color: #66b1ff"  >更多<i class="el-icon-arrow-down"></i></el-button>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="changePageSize"
          @current-change="turnToPage"
          :current-page="queryInfo.pageIndex"
          :page-sizes="[5, 10, 20, 50, 100, 200]"
          :page-size="queryInfo.pageSize "
          layout="total, prev, pager, next, sizes, jumper"
          :total="totalPage"
          id="div-e-paging-id">
        </el-pagination>
      </div>
    </div>
    <ent-add-or-update v-if="componentIs('ent-add-or-update')" :changeComponent="changeComponent" :isAdd="true"></ent-add-or-update>
    <personal-add-or-update v-if="componentIs('personal-add-or-update')" :changeComponent="changeComponent" :isAdd="true"></personal-add-or-update>
<!--    <add v-if="componentIs('add')" :changeComponent="changeComponent" :componentFlag='componentFlag' :isAdd="true"></add>-->
    <ent-details v-if="componentIs('ent-details')" :id="customerId"></ent-details>
    <personal-details v-if="componentIs('personal-details')" :id="customerId"></personal-details>
    <el-dialog
      title=""
      :visible.sync="selectEmployeeDialogVisible"
      top="20vh"
      width="35%">
      <h3 slot="title">
        选择部门/人
      </h3>
      <div style="border: 1px solid #DDDDDD;border-radius: 2px;height: 30vh;overflow: auto;margin: 0 40px 28px 40px;padding: 13px 20px">
        <el-tree :data="employeeTreeList" ref="employeeQueryTreeRefs" :props="defaultProps" @node-click="employeeHandleNodeClick "></el-tree>
      </div>
      <span style="display: flex;justify-content: center;">
        <el-button @click="selectEmployeeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickSelectEmployeeSearch">确 认</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title=""
      :visible.sync="selectEmployeeTransferDialogVisible"
      top="20vh"
      width="35%"
      @closed="()=>{this.employeeId=null;this.customerIdList=[];this.$refs.multipleTable.clearSelection()}">
      <span slot="title">
        选择部门/人
      </span>
      <div style="border: 1px solid #DDDDDD;border-radius: 2px;height: 30vh;overflow: auto;margin: 0 40px 28px 40px;padding: 13px 20px">
        <el-tree :data="employeeTreeList" ref="employeeTransferTreeRefs" :props="defaultProps" @node-click="employeeTransferHandleNodeClick "></el-tree>
      </div>
      <span style="display: flex;justify-content: center;">
        <el-button @click="selectEmployeeTransferDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickConfirmTransfer">确 认</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title=""
      :visible.sync="selectAreaDialogVisible"
      top="20vh"
      width="35%">
      <h3 slot="title">
        选择地区
      </h3>
      <div style="border: 1px solid #DDDDDD;border-radius: 2px;height: 30vh;overflow: auto;margin: 0 40px 28px 40px;padding: 13px 20px">
        <el-tree :data="areaTreeList" :props="areaTreeProps" @node-click="areaHandleNodeClick" ></el-tree>
      </div>
      <span style="display: flex;justify-content: center;">
        <el-button @click="selectAreaDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickSelectAreaSearch">确 认</el-button>
      </span>
    </el-dialog>
    <add-cooperation-dialog :id="rowData.id" :name="rowData.name" @dialogVisibleChange="cooperationDialogVisibleChange" :dialogVisible="addCooperationDialogVisible" @refreshData="refreshData"></add-cooperation-dialog>
  </div>
</template>

<script>
import BasePaging from '../../common/BasePaging'
import ElTreeSelect from '../../../components/treeSelect/index.vue'
import EntAddOrUpdate from './potentialClientsComponent/enterpriseCustomer/ent-add-or-update'
import Add from './potentialClientsComponent/add'
import EntDetails from './potentialClientsComponent/enterpriseCustomer/ent-details'
import PersonalDetails from './potentialClientsComponent/personalCustomer/personal-details'
import {getDepartTree} from '../../../api/depart'
import PersonalAddOrUpdate from './potentialClientsComponent/personalCustomer/personal-add-or-update'
import { paging } from '../../../api/customer/potential'
import { getAreaTree } from '../../../api/customer/region'
import {isAuth} from '../../../utils'
import BatchImport from './Component/BatchImport'
import { customerExport, transferCustomerBatch } from '../../../api/customer/enterprise'
import AddCooperationDialog from './Component/AddCooperationDialog'
import {deleteCustomer} from '../../../api/customer/regionalList'
const isObjHasKey = require('lodash/has')
export default {
  name: 'potential-clients',
  components: {
    AddCooperationDialog,
    BatchImport,
    PersonalAddOrUpdate,
    PersonalDetails,
    EntDetails,
    Add,
    EntAddOrUpdate,
    ElTreeSelect},
  extends: BasePaging,
  created () {
    this.adjustTableHeight()
    // this.getAreaTree()
    if (isAuth('potential:paging')) { this.paging() }
  },
  data () {
    return {
      params: {
        followUserId: '',
        name: '',
        areaId: '',
        cityId: '',
        certificateCode: '',
        contactsName: '',
        contactsMobile: '',
        deptId: ''
      },
      // 转成交行数据
      rowData: {},
      employeeId: '',
      customerId: '',
      customerIdList: [],
      labelPosition: 'right',
      selectEmployeeTransferDialogVisible: false,
      selectEmployeeDialogVisible: false,
      selectAreaDialogVisible: false,
      addCooperationDialogVisible: false,
      // tabs切换FLag enterprise,personal
      tabsFlag: 'enterprise',
      // 组件切换Flag  potential-clients,ent-add-or-update
      componentFlag: 'potential-clients',
      dataListLoading: false,
      employeeSelectValue: '',
      areaSelectValue: '',
      areaTreeList: [],
      employeeTreeList: [],
      tableData: [
        {name: '企业'}
      ],

      areaTreeProps: {
        children: 'children',
        label: 'name'
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      managerOptions: []
    }
  },
  methods: {
    isAuth (auth) {
      return isAuth(auth)
    },
    initParmas () {
      Object.keys(this.params).forEach((key) => {
        this.params[key] = ''
      })
    },
    refreshData () {
      this.initParmas()
      this.paging()
    },
    paging () {
      this.dataListLoading = true
      let requestData = {
        conditions: {
          'typeId': 2
        },
        'inOrder': this.inOrder,
        'orderBy': this.orderBy,
        'pageNum': this.queryInfo.pageIndex,
        'pageSize': this.queryInfo.pageSize
      }
      if (this.tabsFlag === 'enterprise') {
        // 1为企业客户
        requestData.conditions.enterpriseFlag = 1
        requestData.conditions.followUserId = this.params.followUserId
        requestData.conditions.name = this.params.name
        requestData.conditions.cityId = this.params.cityId
        requestData.conditions.areaId = this.params.areaId
        requestData.conditions.certificateCode = this.params.certificateCode
        requestData.conditions.deptId = this.params.deptId
      } else {
        // 2为个人客户
        requestData.conditions.enterpriseFlag = 0
        requestData.conditions.followUserId = this.params.followUserId
        requestData.conditions.contactsName = this.params.contactsName
        requestData.conditions.contactsMobile = this.params.contactsMobile
        requestData.conditions.deptId = this.params.deptId
      }

      paging(
        '/ent/customer/paging',
          requestData,
        'post',
        (data) => {
          this.tableData = data.data.records
          this.totalPage = data.data.total
          this.dataListLoading = false
        }

      )
    },
    // 判断当前什么组件
    componentIs (val) {
      return this.componentFlag === val
    },
    // 更改组件显示
    changeComponent (to) {
      this.componentFlag = to
      this.initParams()
      this.paging()
    },
    clickShowDetails (val, row) {
      this.changeComponent(val)
      this.customerId = row.id
    },
    // 初始化表单
    initAllocateForm () {

    },
    // 初始化搜索参数
    initParams () {
      Object.keys(this.params).forEach((key) => {
        if (Array.isArray(this.params[key])) {
          this.params[key] = []
        } else {
          this.params[key] = ''
        }
      })
      this.employeeSelectValue = ''
      this.areaSelectValue = ''
    },
    // 清除企业名称
    clearName () {
      this.params.name = ''
      this.clickSearch()
    },
    // 显示部门/人选择框
    showSelectEmployeeDialog () {
      this.getEmployeeTree(2)
      this.selectEmployeeDialogVisible = true
    },
    // 显示部门/人选择框转让
    showSelectEmployeeTransferDialog () {
      this.getEmployeeTree(1)
      this.selectEmployeeTransferDialogVisible = true
    },
    clickTransferSingle (row) {
      this.customerIdList = []
      this.customerIdList.push(row.id)
      this.showSelectEmployeeTransferDialog()
    },
    // 点击删除客户
    clickDelete (row) {
      this.$confirm(`确认要删除“${row.name}”吗？`, '提示', {
        confirmButtonText: '确 认',
        cancelButtonText: '取 消',
        type: 'warning'
      }).then(() => {
        deleteCustomer(row.id, () => { this.paging() })
/*        removeCustomer(row.id,
          () => {
            this.$message.success('移除成功!')
            this.paging()
          }) */
      })
      this.paging()
    },
    // 清除部门/人选择框
    clearEmployee () {
      this.params.followUserId = ''
      this.clearSearch()
    },
    // 部门人(搜索)点击监听
    employeeHandleNodeClick (nodeObj, node) {
      this.employeeSelectValue = node.data.name
      if (node.isLeaf) {
        this.params.deptId = null
        this.params.followUserId = node.data.id
      } else {
        this.params.followUserId = null
        this.params.deptId = node.data.id
      }
    },
    employeeTransferHandleNodeClick (node) {
      this.employeeId = node.id
    },
    clickConfirmTransfer () {
      let curNode = this.$refs.employeeTransferTreeRefs.getCurrentNode()
      if (this.customerIdList && this.employeeId) {
        // 用来判断选择是否是部门
        let isDept = isObjHasKey(curNode, 'userList')
        if (!isDept) {
          this.$prompt('请输入转让日志', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            inputErrorMessage: '转让日志不得为空!',
            inputValidator: function (value) {
              return !!value
            }
          }).then(({value}) => {
            transferCustomerBatch({customerIdList: this.customerIdList, userId: this.employeeId, remark: value},
              () => {
                this.$message.success('转让成功!')
                this.paging()
              })
            this.selectEmployeeTransferDialogVisible = false
          })
        } else {
          this.$message.warning('只能转让给部门下的人员，重新选择。')
        }
      } else {
        this.selectEmployeeTransferDialogVisible = false
      }
    },
    // 显示区域对话框
    showSelectAreaDialog () {
      this.getAreaTree()
      this.selectAreaDialogVisible = true
    },
    // 清除区域
    clearArea () {
      this.params.cityId = ''
      this.params.areaId = ''
      this.clickSearch()
    },
    // 区域树点击监听
    areaHandleNodeClick (ndoeObj, node) {
      this.areaSelectValue = node.data.name
      if (node.isLeaf) {
        this.params.cityId = ''
        this.params.areaId = node.data.id
      } else {
        this.params.areaId = ''
        this.params.cityId = node.data.id
      }
    },

    // 获取部门人树
    getEmployeeTree (action = 2) {
      getDepartTree(
        action,
        (data) => {
          this.transformEmployeeTreeData(data.data)
          this.employeeTreeList = data.data
        }
      )
    },
    // 部门人员数据转换为符合组件使用的类型
    transformEmployeeTreeData (data = []) {
      if (data) {
        data.forEach((item) => {
          item.name = item.deptName
          if (item.children && item.userList) {
            this.transformEmployeeTreeData(item.children)
            item.children = item.children.concat(item.userList)
          } else if (!item.children && item.userList) {
            item.children = item.userList
          }
        })
      }
    },
    // 获取区域树
    getAreaTree () {
      getAreaTree({'actionId': 1},
        (data) => { this.areaTreeList = data.data })
    },

    enterpriseHandleSelectionChange (selection) {
      this.customerIdList = selection.map(item => item.id)
    },
    personalHandleSelectionChange (selection) {
      this.customerIdList = selection.map(item => item.id)
    },
    // 点击添加
    clickAdd () {
      if (this.tabsFlag === 'enterprise') {
        this.changeComponent('ent-add-or-update')
      } else {
        this.changeComponent('personal-add-or-update')
      }
    },
    // 调节table高度
    getOtherHeight () {
      return 36
    },
    // 判断当前Tab是啥
    tabIs (tabFlag) {
      return this.tabsFlag === tabFlag
    },
    // 标签点击事件
    clickTabChange (tab) {
      this.tabsFlag = tab
      this.tableData = []
      this.initAllocateForm()
      this.initParams()
      this.paging()
    },
    // 查询条件重置
    clickReset () {
      this.initParams()
      this.paging()
    },
    // 清空搜索条件
    clearSearch () {
      this.paging()
    },
    clearContactsName () {
      this.clickSearch()
    },
    clearContactsMobile () {
      this.clickSearch()
    },
    clickExport () {
      let data = {'typeId': 2, 'enterpriseFlag': 1, ...this.params}
      let fileName = '企业意向客户'
      if (this.tabsFlag === 'personal') {
        data.enterpriseFlag = 0
        fileName = '个人意向客户'
      }
      customerExport(data, fileName)
    },
    cooperationDialogVisibleChange (val) {
      this.addCooperationDialogVisible = val
    },
    turnToFinishReq (row) {
      // console.log('row', row)
      this.rowData = row
      this.addCooperationDialogVisible = true
    },
    // 把表格固定行添加右分隔线
    cellStyle ({row, column, rowIndex, columnIndex}) {
      console.log('columnIndex', columnIndex)
      if (columnIndex === 3) {
        return 'borderLeft:2px solid #6E92E9'
      } else {
        return ''
      }
    },
    clickSelectAreaSearch () {
      this.clickSearch()
      this.selectAreaDialogVisible = false
    },
    clickSelectEmployeeSearch () {
      this.clickSearch()
      this.selectEmployeeDialogVisible = false
    }

  }
}
</script>



